<?php
/**
 * TODO: Add loging
 *
 */

/**
 * @see Zend_Loader
 */
require_once 'Zend/Loader.php';
require_once 'Zend/Gdata.php';
require_once 'Zend/Debug.php';

/**
 * @see Zend_Gdata_ClientLogin
 */
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');

/**
 * @see Zend_Gdata_Finance
 */
Zend_Loader::loadClass('Zend_Gdata_Finance');

/**
 * Returns a HTTP client object with the appropriate headers for communicating
 * with Google using the ClientLogin credentials supplied.
 *
 * @param  string $user The username, in e-mail address format, to authenticate
 * @param  string $pass The password for the user specified
 * @return Zend_Http_Client
 */

function getClientLoginHttpClient($user, $pass)
{
	$service = Zend_Gdata_Finance::AUTH_SERVICE_NAME;
	$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
	return $client;
}

/**
 * Display list of valid commands.
 *
 * @param  string $executable The name of the current script. This is usually av
 ailable as $argv[0].
 * @return void
 */
function displayHelp($executable)
{
	echo "Usage: php {$executable} [<username>] [<password>] " .
        "[<transactions>|<returns>]\n";
}

if (isset($argc) && $argc >= 3)
{
	try {
		$client = getClientLoginHttpClient($argv[1], $argv[2]);
		$gdata = new Zend_Gdata_Finance($client);
		$gdata->enableRequestDebugLogging('/tmp/zend_debug.txt');
	} catch (Zend_Gdata_App_AuthException $e) {
		echo "Error: Unable to authenticate. Please check your";
		echo " credentials.\n";
		exit(1);
	}

}
else
{
	displayHelp($argv[0]);
	exit(1);
}

if ($argv[4] == "returns" )
	echo "portfolio,symbol,name,exchange,shares,costBasis,marketValue,gain,daysGain,gainPercentage,returnOverall,return1w,return4w,return3m,returnYTD,return1y,return3y,return5y\n";
else
    echo "portfolio,symbol,name,exchange\n";


$feed=$gdata->getPortfolioFeed();
# Iterate over the portfolio entries in the feed and display each portfolio  title.
  foreach ($feed->entries as $portfolio)
  	{
  		$positions = $gdata->getPositionFeed($portfolio->id. "/positions?returns=true" );
  	

foreach ( $positions as $entry ) 
{
  	$pdata =  $entry->getPositionData();
  	$symbol=$entry->getSymbol();
	echo $portfolio->title ,  "," , $symbol->symbol , ",";
	echo $symbol->exchange , "," , str_replace(",", " " , $symbol->getFullName());
    
	if ($argv[4] == "returns" )
	{
	echo "," . $pdata->getCostBasis()->getMoney()->getAmount(). ",";
	echo $pdata->getMarketValue()->getMoney()->getAmount() . ",";	
	echo $pdata->getGain()->getMoney()->getAmount() . ",";
	echo $pdata->getDaysGain()->getMoney()->getAmount() . ",";	
	echo $pdata->getGainPercentage() , ",";	
	echo $pdata->getReturnOverall() , ",";	
	echo $pdata->getReturn1w() , ",";	
	echo $pdata->getReturn4w() , ",";	
	echo $pdata->getReturn3m() , ",";	
	echo $pdata->getReturnYTD() , ",";	
	echo $pdata->getReturn1y() , ",";	
	echo $pdata->getReturn3y() , ",";	
	echo $pdata->getReturn5y();
    }
	echo "\n";

}	
  	}
?>
